<template>
  <div class="flex flex-col h-full p-4 gap-4">
    <!-- 组织信息展示区块 -->
    <div class="bg-white rounded-lg shadow p-6">
      <div class="flex items-center gap-1 mb-4 pb-4 border-b">
        <h2 class="text-lg font-medium">Organization Info</h2>
        <el-button type="primary" link @click="openEditDialog">
          <el-icon><Edit /></el-icon>
        </el-button>
      </div>
      <div class="flex flex-col gap-4">
        <div class="flex items-center">
          <span class="text-gray-500 w-40">Organization name:</span>
          <span>{{ organizationInfo.name }}</span>
        </div>
        <div class="flex items-center">
          <span class="text-gray-500 w-40">Organization type:</span>
          <span>{{ organizationInfo.type }}</span>
        </div>
        <div class="flex items-center">
          <span class="text-gray-500 w-40">Country/Region:</span>
          <span>{{ organizationInfo.country }}</span>
        </div>
        <div class="flex items-center">
          <span class="text-gray-500 w-40">Organization address:</span>
          <span>{{ organizationInfo.address }}</span>
        </div>
        <div class="flex items-center">
          <span class="text-gray-500 w-40">Organization E-mail:</span>
          <span>{{ organizationInfo.email }}</span>
        </div>
      </div>
    </div>

    <!-- 设置弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="Setting"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="editForm"
        :rules="formRules"
        ref="editFormRef"
        label-width="180px"
        label-position="right"
      >
        <el-form-item prop="name">
          <template #label> Organization name : </template>
          <el-input
            v-model="editForm.name"
            placeholder="Please enter"
            :maxlength="100"
            :show-word-limit="true"
          />
        </el-form-item>

        <el-form-item prop="country">
          <template #label> Country/Region : </template>
          <el-select
            v-model="editForm.country"
            placeholder="Please enter"
            style="width: 100%"
          >
            <el-option label="China" value="China" />
            <el-option label="Germany" value="Germany" />
            <el-option label="France" value="France" />
            <el-option label="Australia" value="Australia" />
            <el-option label="Netherlands" value="Netherlands" />
            <el-option label="Sweden" value="Sweden" />
            <el-option label="United States" value="United States" />
            <el-option label="Japan" value="Japan" />
          </el-select>
        </el-form-item>

        <el-form-item prop="address">
          <template #label>Organization address : </template>
          <el-input
            v-model="editForm.address"
            placeholder="Please enter"
            :maxlength="100"
            :show-word-limit="true"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="submitEditForm"> OK </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Edit } from "@element-plus/icons-vue";
import { organizationBizApi } from "@/api/business";
import { accountSelfApi } from "@/api/business";
import type { FormInstance, FormRules } from "element-plus";
// 使用 Element Plus 自带图标

// ================================
// 组织信息（Organization Info）页面脚本逻辑
// - 职责：展示组织（公司/机构）基础信息，并允许编辑组织名称、国家/地区与地址
// - 数据来源：
//   1) 优先使用当前账号 ID（user.id）调用详情接口，由后端根据 ID 判定并返回组织信息
//   2) 若 user.id 不存在，再尝试使用 deptId 兜底
// - 主要交互：
//   1) 点击右上角“笔”按钮打开设置弹窗（Setting）
//   2) 在弹窗中修改组织名称、国家/地区、地址并提交，成功后刷新展示区
// - 表单校验：必填 + 长度等基础规则
// ================================

// 组织信息（从接口加载，store 仅用于取初始ID）
import { useAppStore } from "@/store";
const appStore = useAppStore();

// 1) 展示用组织信息对象：页面顶部信息区直接读取此处字段
//    - 初始不依赖 store，统一通过接口获取后回填
const organizationInfo = reactive({
  id: "",
  name: "",
  type: "",
  country: "",
  address: "",
  email: ""
});

// 2) 设置弹窗：显隐状态 + 表单引用 + 表单模型（仅编辑必要字段）
const editDialogVisible = ref(false);
const editFormRef = ref<FormInstance>();
const editForm = reactive({
  name: "",
  country: "",
  address: ""
});

// 3) 表单校验规则：名称/国家/地址的必填与长度限制
const formRules = reactive<FormRules>({
  name: [
    {
      required: true,
      message: "Please enter organization name",
      trigger: "blur"
    },
    {
      min: 8,
      max: 100,
      message: "Length should be 8 to 100 characters",
      trigger: "blur"
    }
  ],
  country: [
    {
      required: true,
      message: "Please select country/region",
      trigger: "change"
    }
  ],
  address: [
    {
      required: true,
      message: "Please enter organization address",
      trigger: "blur"
    },
    {
      min: 8,
      max: 100,
      message: "Length should be 8 to 100 characters",
      trigger: "blur"
    }
  ]
});

// 4) 打开设置弹窗：将当前展示数据复制到表单模型中，方便用户编辑
const openEditDialog = () => {
  // Copy current organization info to edit form
  editForm.name = organizationInfo.name;
  editForm.country = organizationInfo.country;
  editForm.address = organizationInfo.address;

  editDialogVisible.value = true;
};

// 5) 提交编辑：
//    a. 触发表单校验
//    b. 通过后调用 organizationBizApi.update 按接口字段要求提交
//    c. 成功后同步回填展示区字段并提示成功，关闭弹窗
const submitEditForm = async () => {
  if (!editFormRef.value) return;
  const valid = await editFormRef.value.validate();
  if (valid) {
    await organizationBizApi.update({
      id: organizationInfo.id,
      organizationName: editForm.name,
      countryRegion: editForm.country,
      organizationAddr: editForm.address
    } as any);
    organizationInfo.name = editForm.name;
    organizationInfo.country = editForm.country;
    organizationInfo.address = editForm.address;
    ElMessage.success("Organization info updated successfully!");
    editDialogVisible.value = false;
  } else {
    ElMessage.error("Please fix the form errors");
  }
};

onMounted(() => {
  // 6) 页面挂载后加载组织详情：
  //    - 优先使用当前账号ID（user.id）作为查询ID
  //    - 若无，则尝试使用 deptId 兜底
  const loadById = (id: string) => {
    console.log('请求组织详情，id:', id);
    organizationBizApi.getById(String(id)).then((res: any) => {
      console.log('组织详情接口返回:', res);
      if (res && res.code === 0) {
        const d = res.data || {};
        organizationInfo.name = d.organizationName || d.name || organizationInfo.name;
        organizationInfo.type = String(d.organizationType ?? d.type ?? "");
        organizationInfo.country = d.countryRegion || d.country || "";
        organizationInfo.address = d.organizationAddr || d.address || "";
        organizationInfo.email = d.organizationEmail || d.email || organizationInfo.email;
      }
    });
  };

  accountSelfApi.getInfo().then((info: any) => {
    console.log('个人信息接口返回:', info);
    if (info && info.code === 0) {
      const d = info.data || {};
      const resolvedId = d.id;
      console.log('用于查询的ID解析:', { userId: d.id, resolvedId });
      if (resolvedId) {
        organizationInfo.id = String(resolvedId);
        organizationInfo.name = d.username || d.deptName || organizationInfo.name;
        organizationInfo.email = d.email || organizationInfo.email;
        loadById(String(resolvedId));
      } else {
        console.warn('个人信息中缺少 id 与 deptId，无法查询组织信息');
      }
    }
  });
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item__error) {
  color: #f56c6c;
  font-size: 14px;
  line-height: 1.5;
}
</style>
